var fs = require('fs'),
    path = require('path');
process.mixin(GLOBAL, require('sys'));

/**
 * 
 */
//InterfaceStatCollector.prototype.run = function(callback) {
var getInterfaceStats = exports.getInterfaceStats = function(interface) {
  var prev = {};
  var first = true;
  var dir="/sys/class/net/"+interface+"/statistics/";

  return function(callback) {
    //List a directory to iterate through all the files for this interface
    fs.readdir(dir, function (error, dirlist) {
      if(error) {
        callback(false, error);
        return;

      } else {
        var results = {};
        var count = 0;

        dirlist.map(function(file) {
          fs.readFile(path.join(dir, file), process.O_RDONLY, function (error, data) {
            if(error) {
              callback(false, error);
              return;

            } else {
              if(!first) {
                //Calculate the difference between the new value and the previous one
                results[file] = (prev[file]) ? (parseInt(data) - prev[file]) : parseInt(data);

                //Set the previous value for the next run
                prev[file] = parseInt(data);

                if((++count) === dirlist.length) {
                  callback(true, results);
                  return;
                }
              } else {
                prev[file] = parseInt(data);

                if((++count) === dirlist.length) {
                  first = false;
                  callback(false, null);
                  return;
                }
              }
            }
          });
        });

      }
    });

  };

};

